package com.genius.utils;

import cn.hutool.core.util.StrUtil;
import com.genius.enums.ResponseType;
import com.genius.exception.GraceException;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.tm.api.GlobalTransaction;
import io.seata.tm.api.GlobalTransactionContext;

public class TransactionUtils {

    /**
     * 手动开启全局事务
     */
    public static void beginGlobalTransaction(){
        try {
            GlobalTransaction globalTransaction = GlobalTransactionContext.getCurrentOrCreate();
            globalTransaction.begin();
        }catch (TransactionException e){
            e.printStackTrace();
        }
    }

    /**
     * 手动回滚全局事务（处理异常）
     * @param responseType 响应结果
     */
    public static void rollbackGlobalTransaction(ResponseType responseType){
        try{
            // 从当前线程获得XID
            String xid = RootContext.getXID();
            if (StrUtil.isNotBlank(xid)) {
                GlobalTransactionContext.reload(xid).rollback();
            }
        }catch (TransactionException e){
            e.printStackTrace();
        }finally {
            GraceException.display(responseType);
        }
    }

    /**
     * 手动回滚全局事务（抛出异常）
     */
    public static void rollbackGlobalTransaction() throws TransactionException {
        // 从当前线程获得XID
        String xid = RootContext.getXID();
        if (StrUtil.isNotBlank(xid)) {
            GlobalTransactionContext.reload(xid).rollback();
        }
    }
}
